package com.gnerv.sylvanas.plugin.openapi.listener;

import com.gnerv.sylvanas.plugin.openapi.autoconfigure.FrameworkOpenapiConfigProperties;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Component
public class OpenapiApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    private ServerProperties serverProperties;

    @Resource
    private FrameworkOpenapiConfigProperties frameworkOpenapiConfigProperties;

    @Override
    public void onApplicationEvent(@NonNull ApplicationReadyEvent applicationReadyEvent) {
        String host = null;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("get local host exception", e);
        }
        host = host == null ? "localhost" : host;
        Integer port = serverProperties.getPort();
        port = port == null ? 8080 : port;
        String contextPath = serverProperties.getServlet().getContextPath();
        contextPath = contextPath == null ? "" : contextPath;
        String path = frameworkOpenapiConfigProperties.getUrl();
        String protocol = serverProperties.getSsl() == null ? "http" : "https";
        log.info("{}://{}:{}{}{}", protocol, host, port, contextPath, path);
    }
}
